package com.enjoy.xbase.sort;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.enjoy.xbase.R;
import com.enjoy.xbase.sort.model.TabMenu;

import java.util.List;

/**
 * 描述：全屏排序组件
 */
public class SortScreenMenu extends RelativeLayout {

    private LinearLayout tabMenuViewButtom;

    //下拉弹出view容器
    private FrameLayout popupMenuViews;


    //菜单下部分割线
    private int underlineColor;
    //垂直分割线颜色
    private int dividerColor;

    //
    private int tabActiveColor; //文字未选择颜色
    private int tabUnActiveColor;  //文字选中颜色
    private int tabOpenColor;          //文字选中颜色

    //文字大小
    private int menuTextSize = 14;

    //tab选中图标
    private Drawable tabIconOpen;
    private Drawable tabIconCloseUn;//未选择
    private Drawable tabIconClose;//激活

    //遮罩层
    private View maskView;
    private int maskColor = Color.parseColor("#60000000");


    //图片
    private Drawable upIcon;
    private Drawable downIcon;
    private Drawable unIcon;

    private TextView openTab;
    private TextView orderTab;

    //
    private MenuOnClickListener menuOnClickListener;


    public SortScreenMenu(Context context) {
        super(context);
    }

    public SortScreenMenu(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    public SortScreenMenu(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    private void init(Context context, AttributeSet attrs) {
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.SortMenu);
        int tabHeight = typedArray.getDimensionPixelSize(R.styleable.SortMenu_tabHeight, 60);
        //下部分割线
        underlineColor = typedArray.getColor(R.styleable.SortMenu_underlineColor, Color.parseColor("#e0e0e0"));
        //分割线
        dividerColor = typedArray.getColor(R.styleable.SortMenu_dividerColor, Color.parseColor("#e0e0e0"));
        //字体颜色
        tabActiveColor = typedArray.getColor(R.styleable.SortMenu_tab_active_color, Color.parseColor("#03ce97"));
        tabUnActiveColor = typedArray.getColor(R.styleable.SortMenu_tab_un_active_color, Color.parseColor("#454545"));
        tabOpenColor = typedArray.getColor(R.styleable.SortMenu_tab_open_color, tabActiveColor);
        //下拉类图标
        tabIconOpen =typedArray.getDrawable(R.styleable.SortMenu_tab_icon_open);
        tabIconClose =typedArray.getDrawable(R.styleable.SortMenu_tab_icon_close);
        tabIconCloseUn =typedArray.getDrawable(R.styleable.SortMenu_tab_icon_close_un);

        if (tabIconOpen==null){
            tabIconOpen=getResources().getDrawable(R.drawable.ic_screen_up);
        }
        if (tabIconClose==null){
            tabIconClose=getResources().getDrawable(R.drawable.ic_screen_down);
        }
        if (tabIconCloseUn==null){
            tabIconCloseUn=getResources().getDrawable(R.drawable.ic_screen_down);
        }

        menuTextSize = typedArray.getDimensionPixelSize(R.styleable.SortMenu_tabTextSize, 14);

        int iconSize=(int)(sp2px(menuTextSize)*0.8);
        tabIconOpen.setBounds(1, 1, iconSize, iconSize);
        tabIconClose.setBounds(1, 1, iconSize, iconSize);
        tabIconCloseUn.setBounds(1, 1, iconSize, iconSize);


        int w = dip2px(15);
        int h = dip2px(20);
        this.unIcon = drawDraw(w, h, 0);
        this.upIcon = drawDraw(w, h, 1);
        this.downIcon = drawDraw(w, h, 2);


        //创建筛选头部
        LinearLayout tabMenu = new LinearLayout(context);

        LayoutParams params = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, tabHeight);
        tabMenu.setLayoutParams(params);
        tabMenu.setOrientation(LinearLayout.VERTICAL);
        tabMenu.setId(R.id.dropDownMenu_underLine);
        addView(tabMenu, 0);


        //初始化tabMenuView并添加到tabMenuView的参照物
        tabMenuViewButtom = new LinearLayout(context);
        LinearLayout.LayoutParams params1 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 0);
        params1.weight = 1;
        tabMenuViewButtom.setLayoutParams(params1);
        tabMenuViewButtom.setOrientation(LinearLayout.HORIZONTAL);
        tabMenu.addView(tabMenuViewButtom);


        //为tabMenuView添加下划线
        View underLine = new View(getContext());
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 1);
        underLine.setLayoutParams(lp);
        underLine.setBackgroundColor(underlineColor);
        tabMenu.addView(underLine);


    }

    public int dip2px(float dipValue) {
        float scale = getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }
    public int sp2px( float spValue) {
        final float fontScale = getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }

    public void setTabMenuViewButtom(List<TabMenu> tabMenus) {
        LayoutParams plp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        plp.addRule(RelativeLayout.BELOW, R.id.dropDownMenu_underLine);
        maskView = new View(getContext());
        maskView.setLayoutParams(new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
        maskView.setBackgroundColor(maskColor);
        maskView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                closeMenu();
            }
        });

        maskView.setVisibility(GONE);
        maskView.setLayoutParams(plp);
        addView(maskView);

        //
        popupMenuViews = new FrameLayout(getContext());
        popupMenuViews.setVisibility(GONE);
        popupMenuViews.setLayoutParams(plp);
        addView(popupMenuViews);

        for (int i = 0; i < tabMenus.size(); i++) {
            //添加tab
            addTab(tabMenus.get(i), i, tabMenus.size());
            //添加下拉视图
            if (tabMenus.get(i).getType() == 3 && tabMenus.get(i).getPopupView() != null) {
                FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
                tabMenus.get(i).getPopupView().setLayoutParams(layoutParams);
                popupMenuViews.addView(tabMenus.get(i).getPopupView());
                tabMenus.get(i).getPopupView().setVisibility(GONE);
            }
        }
    }

    private void addTab(TabMenu tabMenu, int i, int size) {
        LinearLayout menuItemView = new LinearLayout(getContext());
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.MATCH_PARENT);
        layoutParams.weight = 1;
        menuItemView.setLayoutParams(layoutParams);
        menuItemView.setGravity(Gravity.CENTER);
        menuItemView.setOrientation(LinearLayout.HORIZONTAL);

        //文字
        TextView tab = new TextView(getContext());
        tab.setSingleLine();
        tab.setEllipsize(TextUtils.TruncateAt.END);
        tab.setGravity(Gravity.CENTER);
        tab.setTextSize(TypedValue.COMPLEX_UNIT_PX, menuTextSize);
        tab.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT));
        tab.setText(tabMenu.getName());
        tab.setPadding(dpTpPx(8), dpTpPx(8), dpTpPx(8), dpTpPx(8));

        tab.setTag(tabMenu);
        //

        updateTabShow(tab);

        menuItemView.addView(tab, 0);
        //添加点击事件
        menuItemView.setOnClickListener(new TabOnClickListener(i));

        tabMenuViewButtom.addView(menuItemView);

        //添加分割线
        if (i < size - 1) {
            View view = new View(getContext());
            LinearLayout.LayoutParams layoutParam = new LinearLayout.LayoutParams(dpTpPx(0.5f), ViewGroup.LayoutParams.MATCH_PARENT);
            layoutParam.topMargin = dpTpPx(4);
            layoutParam.bottomMargin = dpTpPx(4);
            view.setLayoutParams(layoutParam);
            view.setBackgroundColor(dividerColor);
            tabMenuViewButtom.addView(view);
        }
    }

    private void updateTabShow(TextView tab) {
        TabMenu tabMenu = (TabMenu) tab.getTag();
        switch (tabMenu.getType()) {
            case 0://跳转
                tab.setTextColor(tabUnActiveColor);
                if (tabMenu.getIconResId() > 0) {
                    switch (tabMenu.getPos()) {
                        case 1:
                            tab.setCompoundDrawablesWithIntrinsicBounds(getContext().getResources().getDrawable(tabMenu.getIconResId()), null, null, null);
                            break;
                        case 2:
                            tab.setCompoundDrawablesWithIntrinsicBounds(null, getContext().getResources().getDrawable(tabMenu.getIconResId()), null, null);
                            break;
                        case 3:
                            tab.setCompoundDrawablesWithIntrinsicBounds(null, null, getContext().getResources().getDrawable(tabMenu.getIconResId()), null);
                            break;
                        case 4:
                            tab.setCompoundDrawablesWithIntrinsicBounds(null, null, null, getContext().getResources().getDrawable(tabMenu.getIconResId()));
                            break;
                    }
                }
                break;
            case 1://单排序
                if (tabMenu.getOrder() == 0) {//未选中
                    tab.setTextColor(tabUnActiveColor);
                } else {
                    tab.setTextColor(tabActiveColor);
                }
                break;
            case 2:
                switch (tabMenu.getOrder()) {
                    case 1: //向上
                        tab.setTextColor(tabActiveColor);
                        tab.setCompoundDrawablesWithIntrinsicBounds(null, null, upIcon, null);
                        break;
                    case 2:
                        tab.setTextColor(tabActiveColor);
                        tab.setCompoundDrawablesWithIntrinsicBounds(null, null, downIcon, null);
                        break;
                    default:
                        tab.setTextColor(tabUnActiveColor);
                        tab.setCompoundDrawablesWithIntrinsicBounds(null, null, unIcon, null);
                        break;
                }
                break;
            case 3:
                if (tabMenu.isOpen()){
                    tab.setTextColor(tabOpenColor);
                    tab.setCompoundDrawablePadding(dpTpPx(1));
                    tab.setCompoundDrawablesWithIntrinsicBounds(null, null, tabIconOpen, null);
                }else{
                    tab.setCompoundDrawablePadding(dpTpPx(1));
                    if (tabMenu.isHasVal()){
                        tab.setTextColor(tabActiveColor);
                        tab.setCompoundDrawablesWithIntrinsicBounds(null, null, tabIconClose, null);
                    }else{
                        tab.setTextColor(tabUnActiveColor);
                        tab.setCompoundDrawablesWithIntrinsicBounds(null, null, tabIconCloseUn, null);
                    }
                }
                break;
        }
    }

    /**
     * 关闭菜单
     */
    public void closeMenu() {
        if (openTab != null) {
            TabMenu tabMenu = (TabMenu) openTab.getTag();
            tabMenu.setOpen(false);
            updateTabShow(openTab);

            if (tabMenu!=null&&tabMenu.getPopupView()!=null){
                tabMenu.getPopupView().setVisibility(GONE);
                tabMenu.getPopupView().setAnimation(AnimationUtils.loadAnimation(getContext(), R.anim.dd_menu_out));
            }
            if (maskView.getVisibility()==VISIBLE){
                maskView.setVisibility(GONE);
                maskView.setAnimation(AnimationUtils.loadAnimation(getContext(), R.anim.dd_mask_out));
            }
            openTab = null;
        }
    }

    public void updateOpenTab(String tabName,boolean hasVal) {
        if (openTab != null) {
            openTab.setText(tabName);
            TabMenu tabMenu = (TabMenu) openTab.getTag();
            if (tabMenu!=null) tabMenu.setHasVal(hasVal);
        }
        closeMenu();
    }

    public void setMenuOnClickListener(MenuOnClickListener menuOnClickListener) {
        this.menuOnClickListener = menuOnClickListener;
    }

    private int dpTpPx(float i) {
        return dip2px(i);
    }

    private Drawable drawDraw(int w, int h, int type) {

        Bitmap bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        Paint p = new Paint();
        p.setColor(type == 1 ? tabActiveColor : tabUnActiveColor);
        p.setAntiAlias(true);
        p.setDither(true);
        //上箭头
        Path path = new Path();
        path.moveTo(w * 0.5f, h * 0.25f);// 此点为多边形的起点
        path.lineTo(w * 0.2f, h * 0.45f);
        path.lineTo(w * 0.8f, h * 0.45f);
        path.close(); // 使这些点构成封闭的多边形
        canvas.drawPath(path, p);

        //下箭头
        p.setColor(type == 2 ? tabActiveColor : tabUnActiveColor);
        Path downPath = new Path();
        downPath.moveTo(w * 0.5f, h * 0.75f);// 此点为多边形的起点
        downPath.lineTo(w * 0.2f, h * 0.55f);
        downPath.lineTo(w * 0.8f, h * 0.55f);
        downPath.close(); // 使这些点构成封闭的多边形
        canvas.drawPath(downPath, p);
        return new BitmapDrawable(getResources(), bitmap);
    }

    class TabOnClickListener implements OnClickListener {
        private int position;

        public TabOnClickListener(int position) {
            this.position = position;
        }

        @Override
        public void onClick(View llv) {
            TextView chickTab = (TextView) ((LinearLayout) llv).getChildAt(0);
            TabMenu tabMenu = (TabMenu) chickTab.getTag();
            if (tabMenu == null) return;
            switch (tabMenu.getType()) {//
                case 0://0-跳转 1-单选 2-双向可选 3-下拉筛选
                    if (openTab != null) {
                        closeMenu();
                    }
                    menuOnClickListener.onMenuClick(chickTab, position, tabMenu);
                    break;
                case 1:
                case 2:
                    if (openTab != null) {
                        closeMenu();
                    }
                    if (chickTab.equals(orderTab)) {//点击同一个tab
                        if (tabMenu.getType() == 2) {
                            tabMenu.setOrder(tabMenu.getOrder() == 2 ? 1 : 2);
                            updateTabShow(chickTab);
                            menuOnClickListener.onOrderChange(chickTab, position, tabMenu.getOrder()==1);
                        }
                    } else {
                        if (orderTab != null) {
                            TabMenu oldTabMenu = (TabMenu) orderTab.getTag();
                            oldTabMenu.setOrder(0);
                            updateTabShow(orderTab);
                        }
                        tabMenu.setOrder(tabMenu.getDefaultOrder());
                        updateTabShow(chickTab);
                        orderTab = chickTab;
                        menuOnClickListener.onOrderChange(chickTab, position, tabMenu.getOrder()==1);;
                    }
                    break;
                case 3:
                    if (chickTab.equals(openTab)) {
                        closeMenu();
                    } else {
                        if (openTab!=null){
                            TabMenu openMenu = (TabMenu) openTab.getTag();
                            if (openMenu != null) {
                                openMenu.setOpen(false);
                                updateTabShow(openTab);
                                if (openMenu.getPopupView()!=null)openMenu.getPopupView().setVisibility(GONE);
                            }
                            popupMenuViews.setVisibility(View.GONE);
                            maskView.setVisibility(GONE);
                        }
                        if (!menuOnClickListener.onMenuClick(chickTab,position,tabMenu)){
                            popupMenuViews.setVisibility(View.VISIBLE);
                            tabMenu.getPopupView().setVisibility(View.VISIBLE);
                            tabMenu.getPopupView().setAnimation(AnimationUtils.loadAnimation(getContext(), R.anim.dd_menu_in));
                            maskView.setVisibility(VISIBLE);
                            maskView.setAnimation(AnimationUtils.loadAnimation(getContext(), R.anim.dd_mask_in));
                            tabMenu.setOpen(true);
                            updateTabShow(chickTab);
                            openTab = chickTab;
                        }else{
                            openTab = chickTab;
                        }
                    }
                    break;
            }
        }
    }

}
